/* eslint-disable */
import moment from 'moment'
import store from '@/store'
import { cloneDeep } from 'lodash'
import router from '@/components/storybook/router'
import JSONbig from 'json-bigint'
import { formatFunction } from '@/utils/format'
import qs from 'qs'
import { apiInterface } from '@/api'
import Vue from 'vue'
/**
 *
 * @param {string} data
 * @returns
 */

export function splitLable (data) {
  if (data && data.length > 16) {
    return data.substring(0, 16) + '...'
  } else {
    return data
  }
}

export function ThousandthNumber (number) {
  var str = number.toString()
  var res = ''
  if (str.includes('.')) {
    var arr = str.split('.')
    var newStr = arr[0]
    var re = /(?=(?!(\b))(\d{3})+$)/g
    newStr = newStr.replace(re, ',')
    res = newStr + '.' + arr[1]
  } else {
    var r = /(?=(?!(\b))(\d{3})+$)/g
    res = str.replace(r, ',')
  }
  return res
}
/**
 * Json group by name
 * @param {*} data
 */
export function JSONGroupbyName (data, Name) {
  var map = {}
  var dest = []
  for (var i = 0; i < data.length; i++) {
    var ai = data[i]
    var aiNameValue = ai[Name]
    if (ai[Name] === null) {
      aiNameValue = 'Null'
    } else {
      if (typeof ai[Name] !== 'string') {
        aiNameValue = ((ai[Name]).toString()).trim()
      }
    }
    ai[Name] = aiNameValue
    if (!map[aiNameValue]) {
      dest.push({
        name: aiNameValue,
        data: [ai]
      })
      map[aiNameValue] = ai
    } else {
      for (var j = 0; j < dest.length; j++) {
        var dj = dest[j]
        if (dj.name === aiNameValue) {
          dj.data.push(ai)
          break
        }
      }
    }
  }
  return dest
}

/**
 * Json group by name
 * @param {[Array]} data
 * @param {[Array]} yList
 */
export function JsonGroupList (dataList, yList) {
  var dest = []
  yList.forEach(item => {
    dest.push({
      name: item,
      data: dataList
    })
  })
  return dest
}

/**
 * filter URL query param value and unescape
 * @param {*} name
 */
export function getUrlQureyParams (name) {
  var reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)', 'i')
  var r = window.location.search.substr(1).match(reg)
  if (r != null) {
    return unescape(r[2])
  }
  return null
}

export const generalConvertJsonToSQL = (json,type) => {
  let sqlstr = ''
  if (json.rules && json.condition) {
    for (let index = 0; index < json.rules.length; index++) {
      if (json.rules[index].condition && json.rules[index].rules.length > 0) {
        sqlstr += ' ( ' + generalConvertJsonToSQL(json.rules[index]) + ' ) '
        if (json.rules.length > 1 && index < json.rules.length - 1) { // index % 2 === 0    index < json.rules.length - 1
          // if (json.rules.length > 1 && index % 2 === 0) {
          sqlstr += json.condition
        }
      } else {
        let condition = json.condition
        if (index === json.rules.length - 1) {
          condition = ''
        }
        sqlstr += generalCondition(json.rules[index], condition,type)
      }
    }
  }
  return sqlstr
}

function generalCondition (rule, condition,type) {
  try {
    // return '"' + rule.key + '" ' + rule.opt + ' "' + rule.value + '" ' + condition + ' '
    let tempData = null
    let key = rule.key
    let option = rule.opt
    let value = rule.value
    if (!key) {
      return ''
    }
    if (rule) {
      try {
        if (rule.type === 'text' || rule.type === 'user' || rule.type === 'datetime' || rule.type === 'date') {
          if (option === 'ilike' || option === 'not ilike') {
            tempData = `"${key}" ${option} '%${value}%' ${condition} `
          } else {
            if(type==='widgetsFilter'&&rule.type === 'datetime'&&(option==='>='||option==='<=')) {
              // filter_sql: "\"create_date\" <=  ('2023-01-09 08:00:00'::timestamp ) at time zone 'Asia/Shanghai'  " 
              tempData= `"${key}" ${option} '(${value}::timestamp) at time zone ${store.state.user.timezoneId}' ${condition} `
            } else if(option === 'between'){
              // if(rule.type === 'datetime') {
              //   tempData = `"${key}" ${option} '${moment(value[0]).utc().format("YYYY-MM-DD HH:mm:ss.000000")}' and '${moment(value[1]).utc().format("YYYY-MM-DD HH:mm:ss.999999")}' ${condition} `
              // }else {
              //   tempData = `"${key}" ${option} '${moment(value[0]).format("YYYY-MM-DD HH:mm:ss.000000")}' and '${moment(value[1]).format("YYYY-MM-DD HH:mm:ss.999999")}' ${condition} `
              // }
              tempData = `"${key}" ${option} '${moment(value[0]).format("YYYY-MM-DD HH:mm:ss.000000")}' and '${moment(value[1]).format("YYYY-MM-DD HH:mm:ss.999999")}' ${condition} `
          }else {
            tempData = `"${key}" ${option} '${value}' ${condition} `
          }
         
        }
        if (option === 'ilike%') {
          tempData = `"${key}" ilike '${value}%' ${condition} `
        }
        if (option === '%ilike') {
          tempData = `"${key}" ilike '%${value}' ${condition} `
        }
        if (rule.type === 'datetime' && value.search(/\{/) > -1) {
          tempData = `["${key}" ${option} ${value}] ${condition} `
        }
        if (rule.type === 'date' && value.search(/\{/) > -1) {
          tempData = `["${key}" ${option} ${value}] ${condition} `
        }
      } else {
        tempData = `"${key}" ${option} ${value} ${condition} `
      }
      if (option === 'is null' || option === 'is not null') {
        tempData = `"${key}" ${option} ${condition} `
      }
      if (option === "=''" || option === "!=''") {
        tempData = `"${key}" ${option} ${condition} `
      }
      if (rule.type === 'text' || rule.type === 'user' || rule.type === 'number') {
        if (option === 'in' || option === 'not in') {
          // let lastValue = value.split(',').join("','")
          // tempData = `"${key}" ${option} (${value}) ${condition} `
          if (Array.isArray(value)) {
            let tempValue = ''
            value.map((ev, iii) => {
              if (iii === value.length - 1) {
                tempValue += `'${ev}'`
              } else {
                tempValue += `'${ev}',`
              }
            })
            tempData = `"${key}" ${option} (${tempValue}) ${condition} `
          } else {
            tempData = `"${key}" ${option} (${value}) ${condition} `
          }
        }
        else if (option === '~*'||option === '!~*') {
          if (Array.isArray(value)) {
            let tempValue = ''
            value.map((ev, iii) => {
              if (iii === value.length - 1) {
                tempValue += `${ev}`
              } else {
                tempValue += `${ev}|`
              }
            })
            tempData = `"${key}" ${rule.caseSensitive?option.replace('*',''):option} '${tempValue}' ${condition} `
          }
        }
      }
      } catch (error) {
        
      }
    }
    return tempData
  } catch (error) {
  }
}

export const mergeCoverData = (originData, newData) => {
  for (const key in newData) {
    if (Object.hasOwnProperty.call(newData, key)) {
      originData[key] = cloneDeep(newData[key])
    }
  }
  return originData
}

/**
 * [fileds format]
 * @param  {Array} data
 * @param  {Array} selectFields
 */
export function formatDataList (data, selectFields, field, gadgetType) {
  if (Array.isArray(data) && Array.isArray(selectFields)) {
    let newData = JSON.parse(JSON.stringify(data))
    data.map((item, index) => {
      for (var key in item) {
        let result = selectFields.find(col => {
          return col[field] === key
        })
        if (gadgetType === 'crudformgadget' && result && (result.businessType === 'date' || result.businessType === 'datetime')) {
          item[`date_or_datetime_type_copy_${key}`] = item[key]
        }
        if (result && result.businessType) {
          switch (result.businessType) {
            case 'text':
              item[key] = generalTextFormat(item[key], result.fieldsFormat ? result.fieldsFormat : '')
              break
            case 'boolean':
              item[key] = generalBooleanFormat(item[key], result.fieldsFormat ? result.fieldsFormat : 'True/False')
              break
            case 'date':
              item[key] = generalDateFormat(item[key], result.fieldsFormat ? result.fieldsFormat : 'YYYY-MM-DD')
              break
            case 'datetime':
              item[key] = generalDateTimeFormat(item[key], result.fieldsFormat ? result.fieldsFormat : 'YYYY-MM-DD HH:mm:ss',result.timezoneChecked)
              break
            case 'currency':
              item[key] = generalCurrencyFormat(item[key], result.fieldsFormat ? result.fieldsFormat : '-$0')
              break
            case 'number':
              // item[key] = generalNumberFormat(item[key], result.fieldsFormat ? result.fieldsFormat : '', gadgetType)
              item[key] = formatFunction('number', item[key], result)
              break
            case 'hyperlinks':
              item[key] = generalHyperLinksFormat(item[key], result.fieldsFormat ? result.fieldsFormat : '', gadgetType, result.isNewPage, newData[index], selectFields)
              break
            default:
              item[key] = item[key]
              break
          }
        }
      }
    })
  }
  return data
}
export function generalHyperLinksFormat (dataStr, pattern, gadgetType, isNewPage, rowData, selectFields) {
  if (pattern === null || pattern.trim().length === 0) return dataStr
  if ((gadgetType === 'gridgadget' || gadgetType === 'crudformgadget' || gadgetType === 'checklistgadget' || gadgetType === 'hierarchygridgadget' || gadgetType === 'crudformplusgadget') && (dataStr || dataStr === 0)) {
    if (pattern === 'ConnectWise Ticket URL' || pattern.indexOf('cwticketid_') > -1) {
      return `<a href="https://${store.state.user.domainUrl.cwUrl}/v4_6_release/ConnectWise.aspx?routeTo=ServiceFV&recid=${dataStr}" target="${isNewPage ? '_self' : '_blank'}" style="cursor: pointer;color:#1F6493">` + dataStr + `</a>`
    } else
      if (pattern === 'ConnectWise TimeEntry URL' || pattern.indexOf('cwtimeentry_') > -1) {
        return `<a href="https://${store.state.user.domainUrl.cwUrl}/?usehttps=1&appredirect=?routeTo=TimeEntryFV&recid=${dataStr}" target="${isNewPage ? '_self' : '_blank'}" style="cursor: pointer;color:#1F6493">` + dataStr + `</a>`
      } else
      if (pattern === 'AutoTask Ticket URL' || pattern.indexOf('autotaskticket_') > -1) {
        var result = selectFields.find(item => item.columnName === 'ticket_id')
        if (result) {
          return `<a href="https://${store.state.user.domainUrl.autotaskUrl}/Mvc/ServiceDesk/TicketDetail.mvc?workspace=False&ticketId=${rowData[result.alias]}" target="${isNewPage ? '_self' : '_blank'}" style="cursor: pointer;color:#1F6493">` + dataStr + `</a>`
        } else {
          return dataStr
        }
      }  else if (pattern === 'SyncroMSP Ticket URL'|| pattern.indexOf('syncromspticketid_') > -1){
        return  `<a href="https://${store.state.user.domainUrl.syncroMspUrl}/tickets/${dataStr}" target="${isNewPage ? '_self' : '_blank'}" style="cursor: pointer;color:#1F6493">` + dataStr + `</a>`
      } else if (pattern === 'Halo Ticket URL'){
          if(store.state.user.domainUrl.haloUrl.includes('https')) {
            return  `<a href="${store.state.user.domainUrl.haloUrl}/tickets?id=${dataStr}" target="${isNewPage ? '_self' : '_blank'}" style="cursor: pointer;color:#1F6493">` + dataStr + `</a>`
          }else {
            return  `<a href="https://${store.state.user.domainUrl.haloUrl}/tickets?id=${dataStr}" target="${isNewPage ? '_self' : '_blank'}" style="cursor: pointer;color:#1F6493">` + dataStr + `</a>`
          }
        } else if (pattern === 'Huntress Ticket URL') {
          if(store.state.user.domainUrl.huntressUrl.includes('https')) {
            return  `<a href="${store.state.user.domainUrl.huntressUrl}/account/infection_reports/${dataStr}" target="${isNewPage ? '_self' : '_blank'}" style="cursor: pointer;color:#1F6493">` + dataStr + `</a>`
          }else {
            return  `<a href="https://${store.state.user.domainUrl.huntressUrl}/account/infection_reports/${dataStr}" target="${isNewPage ? '_self' : '_blank'}" style="cursor: pointer;color:#1F6493">` + dataStr + `</a>`
          }
      }
          else {
          try {
            pattern = pattern.replace(/\{\{.*?\}\}/g, val => {
              // eslint-disable-next-line
              val = val.replace('{{', '').replace('}}', '')
              if (val === 'Autotask Root URL') {
                return store.state.user.domainUrl.autotaskUrl
              } else if (val === 'Connectwise Root URL') {
                return store.state.user.domainUrl.cwUrl
              } else {
                return rowData[val] === null ? '' : rowData[val]
              }
            })
            pattern = pattern.replace(/\{[\w\s]+\}/g, val => {
              // eslint-disable-next-line
              val = val.replace(/[\{\}]/g, '')
              if (val === 'Autotask Root URL') {
                return store.state.user.domainUrl.autotaskUrl
              } else if (val === 'Connectwise Root URL') {
                return store.state.user.domainUrl.cwUrl
              } else {
                return rowData[val] === null ? '' : rowData[val]
              }
            })
            
          } catch (error) {
            
          }
          return pattern === null ? dataStr :`<a href="${pattern}" target="${isNewPage ? '_self' : '_blank'}" style="cursor: pointer;color:#1F6493">` + dataStr + `</a>`
        }
  } else {
    return dataStr
  }
}
export function generalCurrencyFormat (dataStr, pattern) {
  if (pattern.indexOf('-') > -1) {
    return currencyFormat(Number(dataStr), pattern.substring(1, 2) + ' ', Number(pattern.substring(2, 3)))
  } else {
    return currencyFormat(Number(dataStr), '', Number(pattern))
  }
}

export function generalNumberFormat (dataStr, pattern, gadgetType) {
  if (gadgetType === 'crudformgadget' || gadgetType === 'checklistgadget' || gadgetType === 'crudformplusgadget') {
    return dataStr
  }
  if (dataStr === null) {
    return ''
  }
  if (typeof dataStr === 'string' && dataStr.trim() === '') {
    return ''
  }
  let tempData = JSON.parse(JSON.stringify(dataStr))
  if (pattern.indexOf('k') > -1) {
    return tempData >= 1e3 ? (tempData / 1e3).toFixed(2) + 'k' : tempData
  }
  if (pattern.indexOf('%') > -1) {
    return JSONbig.parse((tempData * 100.00).toFixed(2)) + ' %'
  } else {
    var resultData = currentNumberFormat(tempData, pattern ? JSONbig.parse(pattern) : null)
    return resultData
  }
}
export function generalBooleanFormat (dataStr, pattern) {
  if (dataStr == true ||dataStr == "true" ) {
    return pattern.split('/')[0]
  } else {
    return pattern.split('/')[1]
  }
}

export function generalTextFormat (dataStr, pattern) {
  let temp = dataStr
  if (pattern === 'text-ticket_status') {
    switch (dataStr) {
      case '1':
        temp = '订单待接收'
        break
      case '2':
        temp = '订单已接收'
        break
      case '3':
        temp = '物料分拣中'
        break
      case '4':
        temp = '物料配送中'
        break
      case '5':
        temp = '已完成'
        break
      case '6':
        temp = '已驳回'
        break
      case '7':
        temp = '已撤销'
        break
    }
  }
  if (pattern === 'text-agv_status') {
    switch (dataStr) {
      case '0':
        temp = '准备中'
        break
      case '1':
        temp = '已派发'
        break
      case '2':
        temp = '任务中'
        break
      case '3':
        temp = '已完成'
        break
      case '4':
        temp = '异常'
        break
    }
  }
  if (pattern === 'text-ddj_status') {
    switch (dataStr) {
      case '0':
        temp = '准备中'
        break
      case '1':
        temp = '执行中'
        break
      case '2':
        temp = '已完成'
        break
    }
  }
  return temp
}

export function generalDateFormat (dataStr, pattern) {
  if(!isCanParseByMoment(dataStr)){
    return dataStr
  }
  if (dataStr) {
    let patternStr = pattern || (store.state.user.timeFormat || 'MM/DD/YYYY')
    return moment(dataStr).format(patternStr)
  } else {
    return dataStr
  }
}

export function generalDateTimeFormat (dataStr, pattern,timezoneChecked) {
  if (dataStr) {
    return GlobalTimeformat(dataStr, null, pattern,null,timezoneChecked)
    // return moment.tz(dataStr, store.state.user.timezoneId).format(pattern) + ' ' + store.state.user.timezoneName
  } else {
    return dataStr
  }
}

/**
 * [currency format]
 * @param  {[type]} value
 * @param  {[type]} currency
 * @param  {[type]} decimals
 * @return {[type]}
 */
const digitsRE = /(\d{3})(?=\d)/g
export function currencyFormat (value, currency, decimals) {
  value = parseFloat(value)
  if (!isFinite(value) || (!value && value !== 0)) return ''
  currency = currency != null ? currency : ''
  decimals = decimals != null ? decimals : 0
  var stringified = ''
  stringified = Math.abs(value).toFixed(decimals)
  var _int = ''
  _int = decimals ? stringified.slice(0, -1 - decimals) : stringified
  var i = 0
  i = _int.length % 3
  var head = ''
  head = i > 0 ? (_int.slice(0, i) + (_int.length > 3 ? ',' : '')) : ''
  var _float = ''
  _float = decimals ? stringified.slice(-1 - decimals) : ''
  var sign = ''
  sign = value < 0 ? '-' : ''
  var res = sign + currency + head + _int.slice(i).replace(digitsRE, '$1,') + _float
  // res = res.replace(',', '')
  return res
}

export function currentNumberFormat (value, decimals) {
  value = JSONbig.parse(value)
  if (!isFinite(value) || (!value && value !== 0)) return ''
  decimals = decimals != null ? decimals : 0
  var stringified = ''
  stringified = decimals ? value.toFixed(decimals) : value
  var res = stringified
  return res
}
/**
 * [Global Time format]
 * @param  {[date/datatime]} value
 * @param  {String} timeType
 * @param  {String} dateType
 */
export function GlobalTimeformat (value, timeType, dateType, showbymonday,timezoneChecked=true) {
  if(!isCanParseByMoment(value)){
    return value
  }
  if (value) {
    let pattern = dateType || (store.state.user.timeFormat || 'YYYY-MM-DD')
    if (showbymonday) {
      return moment.tz(value, store.state.user.timezoneId).add(6, 'd').format((dateType || pattern) + ' ' + (timeType || '')) + ' ' // + moment.tz(value, store.state.user.timezoneId).format('zz')
    } else {
      return moment.tz(value, store.state.user.timezoneId).format((dateType || pattern) + ' ' + (timeType || '')) + ' '// + moment.tz(value, store.state.user.timezoneId).format('zz')
    }
  } else {
    return ''
  }
}

/**
 * [Global Date format]
 * @param  {[date/datatime]} value
 * @param  {String} dateType
 */
export function GlobalDateformat (value, dateType, showbymonday) {
  if(!isCanParseByMoment(value)){
    return value
  }
  if (value) {
    let pattern = dateType || (store.state.user.timeFormat || 'MM/DD/YYYY')
    if (value.toString().includes('Z')) {
      value = (value.toString()).replaceAll('Z', '')
    }
    if (showbymonday) {
      return moment(value).add(6, 'd').format(dateType || pattern)
    } else {
      return moment(value).format(dateType || pattern)
    }
  } else {
    return ''
  }
}
/**
 * [close current active page]
 * @param  {String} tabName
 * router ,this page name
 */
export function currentTabRemoveHandle (tabName) {

  if (!tabName) {
    return false
  }
  if (tabName === 'home') {
    return false
  }
  store.state.contentTabs = store.state.contentTabs.filter(item => item.name !== tabName)
  if (store.state.contentTabs.length <= 0) {
    store.state.sidebarMenuActiveName = store.state.contentTabsActiveName = 'home'
    return false
  }
  if (tabName === store.state.contentTabsActiveName) {
    let tab = store.state.contentTabs[store.state.contentTabs.length - 1]
    router.push({
      path: tab.path,
      params: {
        ...tab.params
      },
      query: {
        ...tab.query
      }
    })
    if (tab.name === 'home') {
      router.push({
        name: tab.name,
        params: {
          ...tab.params
        },
        query: {
          ...tab.query
        }
      })
    } else {
      router.push({
        path: tab.path,
        params: {
          ...tab.params
        },
        query: {
          ...tab.query
        }
      })
    }
  }
}

/**
 * [Keep the decimal places]
 * @param {*} value Origin data
 * @param {*} n Number
 * @param {*} comType computed type + - * /
 * @param {*} comNum computed number 100 1000
 * @returns {String}
 */
export function keepDecimalPlaces (value, n, comType = '+', comNum = 0) {
  if (value.toString().length < 12) { // 12 = 17 - 1 - 4
    value = comValue(Number(value), comType, comNum)
    let f = Math.round(value * Math.pow(10, n)) / Math.pow(10, n)
    let s = f.toString()
    let rs = s.indexOf('.')
    if (rs < 0 && n > 0) {
      s += '.'
    }
    for (let i = s.length - s.indexOf('.'); i <= n; i++) {
      s += '0'
    }
    return s
  } else {
    return keepDecimalPlacesBigInt(value, n, comType, comNum)
  }
}

/**
 * [Keep the decimal places for bigint type number]
 * @param {*} value Origin data
 * @param {*} n Number
 * @param {*} comType computed type + - * /
 * @param {*} comNum computed number 100 1000
 * @returns {String}
 */
export function keepDecimalPlacesBigInt (value, n, comType, comNum) {
  // if (n > 8) {
  //   return value
  // }
  let isFushu = false
  if (value < 0) {
    value = value * -1
    isFushu = true
  }
  let temp = value.toString()
  let last = null
  if (temp.includes('.')) {
    let index = temp.indexOf('.')
    if (index > 2) {
      let otherStart = temp.slice(0, index - 3)
      let needCom = 1 + temp.slice(index - 3, index + n + 1 + 1 + 3)
      last = `${otherStart}${keepDecimalP(Number(needCom), n, comType, comNum).toString().slice(1)}`
    } else {
      let needCom = temp.slice(0, index + n + 1 + 1 + 3)
      last = `${keepDecimalP(Number(needCom), n, comType, comNum).toString()}`
    }
  } else {
    let other = temp.slice(0, -10)
    let needCom = 1 + temp.slice(-10)
    last = `${other}${keepDecimalP(Number(needCom), n, comType, comNum).toString().slice(1)}`
  }
  if (isFushu) {

    return last * -1
  } else {
    return last
  }
}
/**
 * [keepDecimalP for format big Number]
 * @param {*} value Origin data
 * @param {*} n Number
 * @param {*} comType computed type + - * /
 * @param {*} comNum computed number 100 1000
 * @returns {String}
 */
export function keepDecimalP (value, n, comType = '+', comNum = 0) {
  value = comValue(value, comType, comNum)
  let f = Math.round(value * Math.pow(10, n)) / Math.pow(10, n)
  let s = f.toString()
  let rs = s.indexOf('.')
  if (rs < 0 && n > 0) {
    s += '.'
  }
  for (let i = s.length - s.indexOf('.'); i <= n; i++) {
    s += '0'
  }
  return s
}

export const comValue = (val, type, num) => {
  switch (type) {
    case '+':
      val = val + num
      break
    case '-':
      val = val - num
      break
    case '*':
      val = val * num
      break
    case '/':
      val = val / num
      break
    default:
      break
  }
  return val
}

export function returnSqlForFields (field) {
  return `convert_timezone("${field}",'${store.state.user.timezoneId}')`
}

export const isJson = str => {
  try {
    const jsonObj = JSON.parse(str)
    if (typeof str === 'string' && typeof jsonObj === 'object') return true
  } catch (error) {
    return false
  }
  return false
}

export function serializeUrl (obj = {}) {
  let str = "";
  for (let key in obj) {
    if (str != "") {
      str += "&";
    }
    str += key + "=" + encodeURIComponent(obj[key]);
  }

  return str
}
/**
 * [hyperLinksTool for format hyperLinks ,return replace data]
 * @param {*} pattern String data
 * @param {*} rowData String
 * @returns {String}
 */
export function hyperLinksTool (dataStr, gadgetType, pattern, rowData, selectFields) {
  if (pattern.trim().length === 0) return dataStr
  if ((gadgetType === 'gridgadget' || gadgetType === 'crudformgadget' || gadgetType === 'checklistgadget' || gadgetType === 'hierarchygridgadget') && (dataStr || dataStr === 0)) {
    if (pattern === 'ConnectWise Ticket URL' || pattern.indexOf('cwticketid_') > -1) {
      return `https://${store.state.user.domainUrl.cwUrl}/v4_6_release/ConnectWise.aspx?routeTo=ServiceFV&recid=${dataStr}`
    } else
      if (pattern === 'ConnectWise TimeEntry URL' || pattern.indexOf('cwtimeentry_') > -1) {
        return `https://${store.state.user.domainUrl.cwUrl}/?usehttps=1&appredirect=?routeTo=TimeEntryFV&recid=${dataStr}`
      } else
        if (pattern === 'AutoTask Ticket URL' || pattern.indexOf('autotaskticket_') > -1) {
          var result = selectFields.find(item => item.columnName === 'ticket_id')
          if (result) {
            return `https://${store.state.user.domainUrl.autotaskUrl}/Mvc/ServiceDesk/TicketDetail.mvc?workspace=False&ticketId=${rowData[result.alias]}`
          } else {
            return dataStr
          }
      } else if (pattern === 'SyncroMSP Ticket URL'|| pattern.indexOf('syncromspticketid_') > -1){
          return `https://${store.state.user.domainUrl.syncroMspUrl}/tickets/${dataStr}`
        }else if (pattern === 'Halo Ticket URL'){
          if(store.state.user.domainUrl.haloUrl.includes('http')) {
            return  `${store.state.user.domainUrl.haloUrl}/tickets?id=${dataStr}`
          }else {
            return  `https://${store.state.user.domainUrl.haloUrl}/tickets?id=${dataStr}`
          }
        } else if (pattern === 'Huntress Ticket URL') {
          if( store.state.user.domainUrl.huntressUrl.includes('http') ) {
            return  `${store.state.user.domainUrl.huntressUrl}/account/infection_reports/${dataStr}`
          }else {
            return  `https://${store.state.user.domainUrl.huntressUrl}/account/infection_reports/${dataStr}`
          }
      } else {
          pattern = pattern.replace(/\{[\w\s]+\}/g, val => {
            // eslint-disable-next-line
            val = val.replace(/[\{\}]/g, '')
            if (val === 'Autotask Root URL') {
              return store.state.user.domainUrl.autotaskUrl
            } else if (val === 'Connectwise Root URL') {
              return store.state.user.domainUrl.cwUrl
            } else {
              return rowData[val] === null ? '' : rowData[val]
            }
          })
          return `${pattern}`
        }
  } else {
    return dataStr
  }
}
// includes "", NaN, null,undefined  but not includes 0  false
export function isNotNullValue (val) {
  if (!val) {
    if (val === NaN || val === null || val === undefined) {
      return false
    } else {
      return true
    }
  } else {
    return true
  }
}

/**
 * @param {String} val
 * Drill down the includes param
 */
export function isHaveQuotationMarks(val) {
  let  valStr = String(val)
  // var reg = RegExp(/ CASE | WHEN | THEN | END |\||::/)
  var reg = RegExp(/\||::/)
  if (reg.exec(valStr.toUpperCase())||(valStr.toUpperCase().includes('CASE')&&valStr.toUpperCase().includes('WHEN')&&valStr.toUpperCase().includes('THEN')&&valStr.toUpperCase().includes('END'))||valStr.toUpperCase().includes('ROUND')) {
    return true
  } else { 
    return false 
  }
}


/**
 * @param {String} val
 * Return strVal UpperCase and not includes '_' and format val string
 */
export function istToUpperCase (val) {
  // let str = ''
  // let strVal=''
  // str = (val.substr(0, 1).toUpperCase() + val.substr(1)).replaceAll('_', ' ')
  // strVal= str.split(' ').map(v => v.substr(0, 1).toUpperCase() + v.substr(1)).join(' ')
  // return strVal
  return val
}

export function getQuery (name) {
  if (router.currentRoute.path === '/home' && name==='pageid') {
    return (store.state.user.homePage || store.state.siteWebConfig.homePage) || 'home'
  }else if(router.currentRoute.query){
    return router.currentRoute.query[name]
  }
}

export function getNextAppInfo (type,name) {
  try {
      let nextTicketAppList = store.state.nextTicket.nextTicketAppList
      let afterId = router.currentRoute.params.afterId
      if(router.currentRoute.path === '/home') {
        afterId = store.state.user.homePage || store.state.siteWebConfig.homePage
      }
      if(router.currentRoute.path === '/nextTicket'){
        afterId = router.currentRoute.query.pageid
      }
      let res = nextTicketAppList.find(item => item.appParam[type] === afterId)
      if(res) {
        return res.appParam[name]
      }
  } catch (error) {
    
  }
}
export function getNextAppAllInfo (type,name) {
  try {
    let nextTicketAppList = store.state.nextTicket.nextTicketAppList
      let afterId = router.currentRoute.params.afterId
      if(router.currentRoute.path === '/home') {
        afterId = store.state.user.homePage || store.state.siteWebConfig.homePage
      }
      let res = nextTicketAppList.find(item => item.appParam[type] === afterId)
      if(res) {
        return res
      }
  } catch (error) {
    
  }
}
export function getDrillthrough(selectFields,data,field) {
  try {
    let res = selectFields.find(item => item.bind === field)
    if (res) {
      let queryId = res.queryId
      let drillthroughList = selectFields.filter(item => item.queryId === queryId && item.dataType === 'dimension')
      let arr = drillthroughList.map((item,index) => {
        return {
          selectField: item,
          value: Object.keys(data).find(i=>i.includes('dimension')) ? data[`dimension${index+1}`] : data[item.bind],
          timezoneId: store.state.user.timezoneId
        }
      })
      return arr
    }
  } catch (error) {
    
  }
}

/// <summary>
/// date or datetime type judge function for value
/// </summary>
export function isCanParseByMoment(str) {

  // if (isDate(str)) return true;  
  // let dateTimeRe = /^\d{4}-\d{2}-\d{2} ?\d{2}:\d{2}:\d{2}$/;
  // if (dateTimeRe.test(str)) return true;  
  // let isoDateTimeRe = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}Z$/;
  // return isoDateTimeRe.test(str);

  let momentObj;
  try {
    momentObj = moment(str);
  } catch (e) {
    return false;
  }  
  return momentObj.isValid(); 
}

const resourcCodeList = {
  '0': 'Report',
  '100': 'Internal_Report',
  '1': 'Widget',
  '110': 'Internal_Widget',
  '2': 'Scorecard',
  '120': 'Internal_Scorecard',
  '3': 'Slicer',
  '130': 'Internal_Slicer',
  '4': 'Bot',
  '140': 'Internal_Bot',
  '5': 'Dataset',
  '150': 'Internal_Dataset',
  '151': 'System_Dataset',
  '6': 'Form',
  '160': 'Internal_Form'
}

export function showErrorWithAssetList(response) {
  try {
    let typeList = this._.groupBy(response.data, 'resourceType')
    let str = ''
    for(var key in typeList) {
      let item = typeList[key]
      str += `<span style="font-weight:700">${resourcCodeList[item[0].resourceType]}:</span>`
      item.forEach((ii,index) => {
        str += `<span>${ii.resourceName}${index === item.length-1 ? '.':','}</span>`
      })
    }
    return this.$message({
      type: 'error',
      duration: 10000,
      message: `<p style="margin-bottom:5px">This role can not be deleted. If you delete this role, the assets under this role will not be accessible,
      please reassign the assets to other roles first and then delete this role.</p>${str}`,
      dangerouslyUseHTMLString: true,
    })
  } catch (error) {
    
  }
};
export function parseQueryString(str) {
  return str.split('&').reduce((acc, curr) => {
    const [key, value] = curr.split('=');
    acc[key] = decodeURIComponent(value || '');
    return acc;
  }, {});
}

export async function filterRole( roleIdList, roleAssignList) {
  roleAssignList = roleAssignList|| await getRoleAssignList()
  let arr = []
  roleIdList.forEach(item => {
    let res = roleAssignList.find(ii => ii.roleId === item)
    if(res) {
      arr.push(item)
    }
  })
  return arr
}

export async function getRoleAssignList() {
  let temp = []
  let roleList = store.state.user.roleList
  roleList.forEach(it => {
    temp.push(it.id)
  })
  let params = qs.stringify(
    {
      roleId: temp,
      tenantCode:store.state.user.tenantCode
    },
    { arrayFormat: 'repeat' }
  )
  const { data: res } = await apiInterface.um.getRoleAssignListApi(params)
  if (res.code !== 0) {
    return this.$message.error(res.msg)
  }
  return res.data || []
}
export function findAncestors(arr, id) {
  const ancestors = [];
  function findParent(node) {
    const parent = arr.find(item => item.id === node.pid);
    if (parent) {
      ancestors.unshift(parent); 
      findParent(parent); 
    }
  }
  const node = arr.find(item => item.id === id);
  if (node) {
    findParent(node);
  }
  return ancestors;
}
